package chapter05_string;


import com.sun.imageio.stream.StreamFinalizer;

/**
 * 描述：替换字符串中连续出现的指定字符串
 *
 * @author hl
 * @date 2021/8/14 15:45
 */
public class Replace {
    public static void main(String[] args) {
        Replace replace = new Replace();
        String result = replace.replace("aaa4", "aa4", "X");
        String result2 = replace.replace2("aaa4", "aa4", "X");
        System.out.println(result);
        System.out.println(result2);
    }

    public String replace(String str, String from, String to){
        if (str == null || from == null || str.equals("") || from.equals("")) {
            return str;
        }
        int match = 0;
        char[] chars = str.toCharArray();
        int i = 0;
        while(i < chars.length) {
            if (chars[i++] == from.charAt(match++)) {
                if (match == from.length()) {
                    for (int j = 1; j <= from.length(); j++) {
                        chars[i - j] = 0;
                    }
                    match = 0;
                }
            }else {
                i = i - match + 1;
                match = 0;
            }
        }
        //拼接
        i = 0;
        char pre = chars[i++];
        String res = pre != 0 ? pre + "" : "";
        while(i < chars.length){
            if (chars[i] != 0) {
                res += pre == 0 ? to + chars[i] : chars[i];
            }
            pre = chars[i++];
        }
        return pre == 0 ? res + to : res;
    }

    public String replace2(String str, String from, String to){
        if (str == null || from == null || str.equals("") || from.equals("")) {
            return str;
        }
        char[] chas = str.toCharArray();
        char[] chaf = from.toCharArray();
        int match = 0;
        for (int i = 0; i < chas.length; i++) {
            if (chas[i] == chaf[match++]) {
                if (match == chaf.length) {
                    clear(chas, i - match + 1, i);
                    match = 0;
                }
            }else {
                i = i - match + 1;
                match = 0;
            }
        }
        String res = "";
        for (int i = 0; i < chas.length; i++) {
            if (chas[i] != 0) {
                res += String.valueOf(chas[i]);
            }
            if(chas[i] == 0 && (i == 0 || chas[i - 1] != 0)){
                res += to;
            }
        }
        return res;
    }

    private void clear(char[] chas, int start, int end) {
        while(start <= end){
            chas[start++] = 0;
        }
    }


}
